import time
from multiprocessing import Process, Pool

import pandas as pd
from QFinanceGridModel.core import Collector

""" 2025/09/03
    个股资金流向df数据去重并根据资金流降序排序完成
"""


class Processor:
    """框架处理器，启动框架，并处理各个模块的交互"""

    def __init__(self) -> None:
        """加载数据"""
        self.__industry_fund_flow_data = None
        self.__concept_fund_flow_data = None
        self.__single_fund_flow_data = None
        self.__get_block_fund_flow_data()

    def __deal_with(self, func, args):  # 异步处理任务
        with Pool() as self.__pool:
            self.__pool.apply_async(func, args)

    def run(self):
        pass

    @property
    def industry_fund_flow_data(self):
        return self.__industry_fund_flow_data

    @property
    def concept_fund_flow_data(self):
        return self.__concept_fund_flow_data

    @property
    def single_fund_flow_data(self):
        return self.__single_fund_flow_data

    def __get_block_fund_flow_data(self):
        temp_list = []  # 临时列表

        """获取行业前10的资金流数据"""
        industry_fund_flow_data = Collector(type="2").run()
        if not industry_fund_flow_data.empty:
            self.__industry_fund_flow_data = industry_fund_flow_data.iloc[:10]
            codes = self.__industry_fund_flow_data["代码"].to_list()
            for code in codes:
                time.sleep(0.25)
                temp_list.append(
                    Collector(
                        type="4",
                        secid=code.split(".")[1]
                    ).run()
                )

        """获取概念前10的资金流数据"""
        industry_fund_flow_data = Collector(type="3").run()
        if not industry_fund_flow_data.empty:
            self.__concept_fund_flow_data = industry_fund_flow_data.iloc[:10]
            codes = self.__concept_fund_flow_data["代码"].to_list()
            for code in codes:
                time.sleep(0.25)
                temp_list.append(
                    Collector(
                        type="4",
                        secid=code.split(".")[1]
                    ).run()
                )

        """将数据合并成总的df并筛选出5千万净流入的个股"""
        self.__single_fund_flow_data = pd.concat(temp_list, ignore_index=True)
        self.__single_fund_flow_data = (
            self.__single_fund_flow_data
            [
                self.__single_fund_flow_data["净流入(亿)"] > 0.5
            ]
            .drop_duplicates(subset=['代码']).sort_values(by=["净流入(亿)"], ascending=False).reset_index(drop=True)
        )


if __name__ == "__main__":
    pd.set_option('display.width', 1000)
    pd.set_option('display.max_rows', None)
    pd.set_option('display.max_columns', None)
    pd.set_option('display.max_colwidth', 50)
    pd.set_option('display.float_format', lambda x: f"{x:,.2f}")
    p = Processor()
    print(p.single_fund_flow_data)
    print(p.industry_fund_flow_data)
    print(p.concept_fund_flow_data)
